using System;
using System.Collections.Generic;

namespace TDUnit.Common.TestData
{
    public class Table
    {
        private readonly List<Row> rows = new List<Row>();

        #region Constructors
        
        public Table(string name, string primaryKeyColumnName, TestData testData) : this(name, primaryKeyColumnName, testData, string.Empty) { }

        public Table(string name, string primaryKeyColumnName, TestData testData, string alias)
        {
            Name = name;
            PrimaryKeyColumnName = primaryKeyColumnName;
            Alias = alias;
            TestData = testData;
        }

        #endregion

        #region Public properties

        public string Name { get; set; }

        public string PrimaryKeyColumnName { get; private set; }

        public bool IsPrimaryKeyAutoIdentity { get; private set; }

        public Row[] Rows
        {
            get
            {
                return rows.ToArray();
            }
        }

        public string Alias { get; set; }

        public TestData TestData{ get; private set;}

        #endregion

        #region Public methods

        public Table WithAutoIdentity(bool isAutoIdetity)
        {
            IsPrimaryKeyAutoIdentity = isAutoIdetity;
            return this;
        }

        public Row GetRow(string name)
        {
            foreach (var r in rows)
            {
                if (r.Name.Equals(name))
                    return r;
            }
            return null;
        }

        public Row AddRow(PrimaryKeyColumn primaryKeyColumn, string name)
        {
            var r = new Row(this, name);
            VerifyRowDoesNotExist(r);
            rows.Add(r);
            return r;
        }

        public Row AddRow(PrimaryKeyColumn primaryKeyColumn)
        {
            return AddRow(primaryKeyColumn, string.Empty);
        }

        #endregion

        #region Overrides

        public override bool Equals(object obj)
        {
            var t = obj as Table;
            return (t != null && t.Name.Equals(Name));
        }

        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }

        public override string ToString()
        {
            return Name;
        }

        #endregion

        #region Helper methods

        private void VerifyRowDoesNotExist(Row row)
        {
            if (string.IsNullOrEmpty(row.Name))
                return;

            foreach (var r in rows)
            {
                if (r.Name.Equals(row.Name))
                    throw new InvalidOperationException(string.Format("A row with name '{0}' already exists in this table.", row.Name));
            }
        }

        #endregion
    }
}